﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Hosting;
using EPiBoost.Core.Interfaces.ContentInterfaces;
using EPiServer;
using EPiServer.Core;
using EPiServer.SpecializedProperties;
using EPiServer.Web;
using EPiServer.Web.Hosting;

namespace EPiBoost.Core.Extensions
{
	public static class LinkItemExtensions
	{
		public static string GetMainTitle(this LinkItem linkItem)
		{
			var epiServerpage = linkItem.GetPage() as IMainTitle;
			if(epiServerpage!=null)
			{
				return epiServerpage.MainTitle;
			}
			return linkItem.Text;
		}
		
		public static PageData GetPage(this LinkItem linkItem)
		{
			PageData result;
			TryParseToPageData(linkItem, out result);
			return result;
		}


		public static string GetHref(this LinkItem linkItem)
		{
			var href = linkItem.GetMappedHref();
			if (string.IsNullOrEmpty(href))
			{
				href = linkItem.Href;
			}
			if (href[0] == '~' && HttpContext.Current != null)
			{
				return System.Web.Mvc.UrlHelper.GenerateContentUrl(href, new HttpContextWrapper(HttpContext.Current));
			}
			return href;
		}
		

		public static bool TryParseToPageData(this LinkItem self, out PageData result)
		{
			return self.TryParseToPageData(out result, null);
		}

		/// <summary>
		/// Tries to parse a LinkItem to a PageData object
		/// </summary>
		/// <param name="self">LinkItem object</param>
		/// <param name="result">The PageData object if it can be parsed - otherwise null</param>
		/// <param name="languageBranch">The language code to return page data's from</param>
		/// <returns>If the LinkItem can be parsed to PageData</returns>
		public static bool TryParseToPageData(this LinkItem self, out PageData result, string languageBranch)
		{
			return UrlExtensions.TryParseToPageData(self.Href, out result, languageBranch);
		}

		public static bool TryParseToUnifiedFile(this LinkItem self, out UnifiedFile result)
		{
			return TryParseToUnifiedFile(self.Href, out result);
		}

		public static bool TryParseToUnifiedFile(string linkUrl, out UnifiedFile result)
		{
			result = null;

			string virtualPath;
			if (PermanentLinkMapStore.TryToMapped(linkUrl, out virtualPath))
			{
				try
				{
					result = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath) as UnifiedFile;

					if (result != null)
					{
						return true;
					}
				}
				catch
				{
					return false;
				}
			}

			return false;
		}
	}
}
